import { Schema } from './schema';
import { Rule, Tree, noop } from '@angular-devkit/schematics';
import { getProjectFromWorkspace } from '@angular/cdk/schematics';
import { getWorkspace } from '@schematics/angular/utility/workspace';
import { WorkspaceDefinition } from '@angular-devkit/core/src/workspace';

const indexHTML = `<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title></title>
    <base href="/" />

    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="icon" type="image/x-icon" href="favicon.ico" />
  </head>
  <body class="bg-light">
    <app-root>
      <div class="preloader">
        <div class="cs-loader">
          <div class="cs-loader-inner">
            <label> ●</label>
            <label> ●</label>
            <label> ●</label>
            <label> ●</label>
            <label> ●</label>
            <label> ●</label>
          </div>
        </div>
      </div>
    </app-root>
  </body>
</html>`;

export function updateIndex(options: Schema): Rule {
  return async (host: Tree) => {
    const workspace = (await getWorkspace(
      host
    )) as unknown as WorkspaceDefinition;
    const project = getProjectFromWorkspace(workspace, options.project);
    const indexHTMLFile = `${project.sourceRoot}/index.html`;
    host.overwrite(indexHTMLFile, indexHTML);

    return noop();
  };
}
